#include "itemdelegate.h"

ItemDelegate::ItemDelegate()
{
}

QWidget * ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() == 0)
    {
        QLineEdit * nameEditor = new QLineEdit(parent);
        return nameEditor;
    }
    else if (index.column() == 1)
    {
        QDateEdit * dateEditor = new QDateEdit(parent);
        dateEditor->setDisplayFormat("d.MM.yyyy");
        dateEditor->setCalendarPopup(true);
        dateEditor->setDate(QDate::currentDate());
        return dateEditor;
    }
    else
    {
        QSpinBox * numberEditor = new QSpinBox(parent);
        numberEditor->setMinimum(-255);
        numberEditor->setMaximum(255);
        return numberEditor;
    }
}

void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if (index.column() == 0)
    {
        QLineEdit * nameEditorData = dynamic_cast<QLineEdit *>(editor);
        nameEditorData->setText(index.model()->data(index, Qt::EditRole).toString());
    }
    else if (index.column() == 1)
    {
        QDateEdit * dateEditorData = dynamic_cast<QDateEdit *>(editor);
        dateEditorData->setDate(QDate::fromString(index.model()->data(index, Qt::EditRole).toString(), "d.MM.yyyy"));
    }
    else
    {
        QSpinBox * numberEditorData = dynamic_cast<QSpinBox *>(editor);
        numberEditorData->setValue(index.model()->data(index, Qt::EditRole).toInt());
    }
}

void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if (index.column() == 0)
    {
        QLineEdit * nameModelData = dynamic_cast<QLineEdit *>(editor);
        model->setData(index, nameModelData->text());
    }
    else if (index.column() == 1)
    {
        QDateEdit * dateModelData = dynamic_cast<QDateEdit *>(editor);
        model->setData(index, dateModelData->date().toString("d.MM.yyyy"));
    }
    else
    {
        QSpinBox * numberModelData = dynamic_cast<QSpinBox *>(editor);
        model->setData(index, numberModelData->value());
    }
}
